package org.apache.rocketmq.client.java.rpc;



import io.grpc.Metadata;
import org.apache.commons.lang3.StringUtils;
import org.apache.rocketmq.client.java.clientapis.ClientConfiguration;
import org.apache.rocketmq.client.java.clientapis.SessionCredentials;
import org.apache.rocketmq.client.java.clientapis.SessionCredentialsProvider;
import org.apache.rocketmq.client.java.misc.MetadataUtils;
import org.apache.rocketmq.client.java.misc.RequestIdGenerator;
import org.apache.rocketmq.client.java.misc.Utilities;

import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Optional;


/**
 * @课程描述:从零带你写框架系列中的课程，整个系列包含netty，xxl-job，rocketmq，nacos，sofajraft，spring，springboot，disruptor，编译器，虚拟机等等。
 * @author：陈清风扬，个人微信号：chenqingfengyangjj。
 * @date:2025/6/10
 * @方法描述：客户端签名工具类
 */
public class Signature {


    public static final String DATE_TIME_KEY = "x-mq-date-time";

    public static final String CLIENT_ID_KEY = "x-mq-client-id";

    public static final String REQUEST_ID_KEY = "x-mq-request-id";

    public static final String LANGUAGE_KEY = "x-mq-language";

    public static final String PROTOCOL_VERSION = "x-mq-protocol";

    public static final String DATE_TIME_FORMAT = "yyyyMMdd'T'HHmmss'Z'";


    private Signature() {
    }

    /**
     * @课程描述:从零带你写框架系列中的课程，整个系列包含netty，xxl-job，rocketmq，nacos，sofajraft，spring，springboot，disruptor，编译器，虚拟机等等。
     * @author：陈清风扬，个人微信号：chenqingfengyangjj。
     * @方法描述：生成客户端签名的方法
     */
    public static Metadata sign(ClientConfiguration config, String clientId) throws NoSuchAlgorithmException, InvalidKeyException {
        //创建元数据对象
        Metadata metadata = new Metadata();
        //设置客户端的编程语言类型
        metadata.put(Metadata.Key.of(LANGUAGE_KEY, Metadata.ASCII_STRING_MARSHALLER), "JAVA");
        //设置Protocol协议版本
        metadata.put(Metadata.Key.of(PROTOCOL_VERSION, Metadata.ASCII_STRING_MARSHALLER), Utilities.getProtocolVersion());
        //设置当前客户端版本
        //metadata.put(Metadata.Key.of(CLIENT_VERSION_KEY, Metadata.ASCII_STRING_MARSHALLER), MetadataUtils.getVersion());
        //得到当前系统时间
        String dateTime = new SimpleDateFormat(DATE_TIME_FORMAT).format(new Date());
        //把时间添加到元数据对象中
        metadata.put(Metadata.Key.of(DATE_TIME_KEY, Metadata.ASCII_STRING_MARSHALLER), dateTime);
        //生成全局唯一的请求Id
        final String requestId = RequestIdGenerator.getInstance().next();
        //把请求Id添加到元数据对象中
        metadata.put(Metadata.Key.of(REQUEST_ID_KEY, Metadata.ASCII_STRING_MARSHALLER), requestId);
        //把客户端Id添加到元数据对象中
        metadata.put(Metadata.Key.of(CLIENT_ID_KEY, Metadata.ASCII_STRING_MARSHALLER), clientId);
        return metadata;
    }
}